//
//  LXPermissionCMPedometer.swift
//  LXPermissionAuth
//
//  Created by yoctech on 2021/8/18.
//

import UIKit
import CoreMotion

@objc class LXPermissionCMPedometer: NSObject, LXPermissionProtocol {
    @objc static let cmPedometer = CMPedometer()

    @objc public static func auth(autoRequestIfNot: Bool, clouser: @escaping LXAuthClouser) {
        if #available(iOS 11.0, *) {
            let aStatus = CMPedometer.authorizationStatus()
            switch aStatus {
            case .restricted:
                clouser(false,  .restricted)
            case .denied:
                clouser(false,  .denied)
            case .authorized:
                clouser(true,  .authorized)
            case .notDetermined:
                if !autoRequestIfNot {
                    clouser(false,  .other)
                    return
                }
                earlierAuth(clouser: clouser)
            @unknown default:
                clouser(false,  .other)
            }
        } else {
            earlierAuth(clouser: clouser)
        }

    }
    
    static func earlierAuth(clouser: @escaping LXAuthClouser) {
        cmPedometer.queryPedometerData(from: Date(), to: Date()) { (pedometerData, error) in
            if pedometerData?.numberOfSteps != nil{
                DispatchQueue.main.async {
                    clouser(true,  .authorized)
                }
            }else{
                DispatchQueue.main.async {
                    clouser(false,  .other)
                }
            }
        }
    }

}
